package com.biostime.qdingding.modules.qd.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.persistence.Page;
import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Coursesection;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.Siginin;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.push.MsgTemplate;
import com.biostime.qdingding.modules.qd.push.MsgTemplate.Absent;
import com.biostime.qdingding.modules.qd.push.MsgTemplate.Sigin;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.CourseService;
import com.biostime.qdingding.modules.qd.service.CoursesectionService;
import com.biostime.qdingding.modules.qd.service.MemberService;
import com.biostime.qdingding.modules.qd.service.MessageService;
import com.biostime.qdingding.modules.qd.service.SigininService;
import com.biostime.qdingding.modules.qd.service.StudentService;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.utils.UserUtils;

/**
 * 签到Controller
 * @author king
 * @version 2015-11-18
 */
@Controller
@RequestMapping(value = "${adminPath}/qd/siginin")
public class SigininController extends BaseController {

	@Autowired
	private SigininService sigininService;
	@Autowired
	private CourseOrderService courseOrderService;
	@Autowired 
	private StudentService studentService;
	@Autowired 
	private MemberService memberService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CoursesectionService coursesectionService;
	@Autowired
	private MessageService messageService;
	
	
	@ModelAttribute
	public Siginin get(@RequestParam(required=false) String id) {
		Siginin entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sigininService.get(id);
		}
		if (entity == null){
			entity = new Siginin();
		} 
		return entity;
	}
	
	@RequiresPermissions(value={"qd:siginin:view","qd:sigin:view"}, logical=Logical.OR)
	@RequestMapping(value = {"list", ""})
	public String list(Siginin siginin, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Siginin> page = sigininService.findPage(new Page<Siginin>(request, response), siginin); 
		model.addAttribute("page", page);
		return "modules/qd/sigininList";
	}
	
	@RequiresPermissions(value={"qd:siginin:edit","qd:sigin:edit"}, logical=Logical.OR)
	@RequestMapping(value ="absent")
	public String absent(HttpServletRequest request, Siginin siginin, Model model){
		String courseId = request.getParameter("courseid");
		String mobile = request.getParameter("mobile");
		String studentName = request.getParameter("studentname");

		Student student = new Student();
		student.setMobile(mobile);
		student.setName(studentName); 
		student = studentService.getfornm(student);
		 
		CourseOrder courseOrder = new CourseOrder();
		courseOrder.setStudentId(Integer.valueOf(student.getId()));
		courseOrder.setCourseId(Integer.valueOf(courseId));
		System.out.println(courseId +"=========================="+ student.getId());
		courseOrder = courseOrderService.getforcsId(courseOrder);

		StringBuilder message = new StringBuilder();
		
		if(!StringUtils.isEmpty(courseOrder.getState()) && !courseOrder.getState().equalsIgnoreCase("ordered")){
			message.append("无法处理旷课 该学生未处于预约状态");
			model.addAttribute("message", message);
			return form(request, siginin, model);
		}
		
		
		siginin.setCourseorderId(Integer.valueOf(courseOrder.getId()));
		
		boolean existSiginin = sigininService.exist(siginin);//查找是否已有签到记录
		if(existSiginin){
				message.append("无法处理旷课 该学生已签到或已作旷课处理 ");
		}else{
			try{
				Siginin sigin = sigininService.absent(courseOrder, siginin);
				
				Course course = sigin.getCourse();
				Student stu = sigin.getStudent();
				Member mem = sigin.getMember();
				
				//发送签到确认消息
				SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
				String msg = Absent.content;
				msg = msg.replace(MsgTemplate.date, df.format(course.getOndate()));
				msg = msg.replace(MsgTemplate.section, course.getSection());
				msg = msg.replace(MsgTemplate.level, course.getClevel());
				msg = msg.replace(MsgTemplate.serial, course.getSerial());
				msg = msg.replace(MsgTemplate.theme, course.getTheme());
				msg = msg.replace(MsgTemplate.count, String.valueOf(sigin.getAbsentCount()));
				
				String pushMsg = Absent.push;
				pushMsg = pushMsg.replace(MsgTemplate.date, df.format(course.getOndate()));
				pushMsg = pushMsg.replace(MsgTemplate.section, course.getSection());
				pushMsg = pushMsg.replace(MsgTemplate.level, course.getClevel());
				pushMsg = pushMsg.replace(MsgTemplate.serial, course.getSerial());
				pushMsg = pushMsg.replace(MsgTemplate.theme, course.getTheme());
				pushMsg = pushMsg.replace(MsgTemplate.count, String.valueOf(sigin.getAbsentCount()));
				
				messageService.sendAndPush(Absent.category, String.valueOf(stu.getId()), Absent.title, msg, String.valueOf(mem.getId()), pushMsg);
				
				message.append("处理旷课 ");
			}catch(Exception ex){
				message.append("处理旷课异常："+ex.getMessage());
				logger.error(String.format("处理旷课[CourseOrder:%s]异常：", courseOrder.getId()), ex);
			}
		}
		model.addAttribute("message", message);
		return form(request, siginin, model);
	}
	
	@RequiresPermissions(value={"qd:siginin:view","qd:sigin:view"}, logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request,Siginin siginin, Model model) {
		
		/**当前考勤课程**/
		String courseId = request.getParameter("courseId");
		if(siginin.getCourse()!=null){
			courseId = siginin.getCourse().getId();
		}
		Course course = courseService.get(courseId);
		
		/**当前时间**/
		Date dateNow = new Date();
		model.addAttribute("dateNow", dateNow.getTime());
		
		User user = UserUtils.getUser();
		
		//Calendar now = Calendar.getInstance();
		//now.add(Calendar.DATE, 2);
		 
		/**时段课程**/
		List<Coursesection> sections = coursesectionService.findListSigns(user,dateNow);
		model.addAttribute("sections", sections);
		
		if(course==null && sections!=null){
			for(Coursesection section : sections){
				if(section.getCourses()!= null && section.getCourses().size()>0){
					course = section.getCourses().get(0);
					break;
				}
			} 
		}
		
		/**签到学员**/
		if(course!=null){
			siginin.setCourse(course);
			List<Siginin> sigininList = sigininService.findListByCourse(siginin);
			model.addAttribute("sigininList", sigininList);
		}
		
		/**签到课程**/
		if(course!=null){
			model.addAttribute("sigininCourseId", course.getId());
		}
		model.addAttribute("siginin", siginin);
		return "modules/qd/sigininForm";
	}

	@RequiresPermissions(value={"qd:siginin:edit","qd:sigin:edit","qd:siginin:add","qd:sigin:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, Siginin siginin, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, siginin)){
			return form(request,siginin, model);
		}
		
		StringBuilder message = new StringBuilder();
		
		CourseOrder courseOrder = courseOrderService.get(new CourseOrder(String.valueOf(siginin.getCourseorderId())));
		
		if(courseOrder==null){
			message.append("您的输入有误，请用扫描枪扫描二维码");
		}else{
			boolean existSiginin = sigininService.exist(siginin);//查找是否已有签到记录
			if(existSiginin){
				message.append("该学员已签到或已做旷课处理"); 
			}else{
				if(!StringUtils.isEmpty(courseOrder.getState()) && !courseOrder.getState().equalsIgnoreCase("ordered")){
					model.addAttribute("message", message);
					message.append("无法处理签到 该学生未处于预约状态");
					return form(request, siginin, model);
				}
				
				try{
					boolean valid = true; 
					//签到时间限制
					Course course1 = courseService.get(String.valueOf(courseOrder.getCourseId()));
					if(course1==null){
						valid = false;
						message.append("无法获取课程信息");
					}else{
						
						String onDate = DateUtils.formatDate(course1.getOndate(),"yyyy-MM-dd");
						String section = course1.getSection();
						
						Date start = null,end = null; 
						try{
							if(!StringUtils.isEmpty(section)){
								String[] sections = section.split("-");
								if(sections!=null && sections.length==2){
									start = DateUtils.parseDate(onDate+" "+sections[0],"yyyy-MM-dd HH:mm");
									end = DateUtils.parseDate(onDate+" "+sections[1],"yyyy-MM-dd HH:mm");
								}else{
									start = DateUtils.parseDate(onDate+" 00:00","yyyy-MM-dd HH:mm");
									end = DateUtils.parseDate(onDate+" 00:00","yyyy-MM-dd HH:mm");
								}
							}
						}catch(Exception ex){
							ex.printStackTrace();
						}
						
						Calendar calendar = Calendar.getInstance();
						
						Date now = new Date();
						
						calendar.setTime(start);
						calendar.add(Calendar.MINUTE, -30);
						
						start = calendar.getTime();
						
						calendar.setTime(end);
						calendar.add(Calendar.MINUTE, 30);
						
						end = calendar.getTime();
						
						logger.info(String.format("[订单编号：%s]允许签到时间范围:%s~%s", courseOrder.getId(), 
								DateUtils.formatDate(start, "yyyy-MM-dd hh:mm"),
								DateUtils.formatDate(end, "yyyy-MM-dd hh:mm")));
						
						if(now.compareTo(start)<0 || now.compareTo(end)>0){
							valid = false;
							message.append("未到签到时间");
						}
					}
					
					if(valid){
						siginin = sigininService.signin(courseOrder, siginin);
						Course course = siginin.getCourse();
						Student student = siginin.getStudent();
						Member member = siginin.getMember();
						
						//发送签到确认消息
						SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
						String msg = Sigin.content;
						msg = msg.replace(MsgTemplate.date, df.format(course.getOndate()));
						msg = msg.replace(MsgTemplate.section, course.getSection());
						msg = msg.replace(MsgTemplate.level, course.getClevel());
						msg = msg.replace(MsgTemplate.serial, course.getSerial());
						msg = msg.replace(MsgTemplate.theme, course.getTheme());
						
						String pushMsg = Sigin.push;
						pushMsg = pushMsg.replace(MsgTemplate.date, df.format(course.getOndate()));
						pushMsg = pushMsg.replace(MsgTemplate.section, course.getSection());
						pushMsg = pushMsg.replace(MsgTemplate.level, course.getClevel());
						pushMsg = pushMsg.replace(MsgTemplate.serial, course.getSerial());
						pushMsg = pushMsg.replace(MsgTemplate.theme, course.getTheme());
						
						messageService.sendAndPush(Sigin.category, String.valueOf(student.getId()), Sigin.title, msg, String.valueOf(member.getId()), pushMsg);
						
						message.append("签到成功");
					}
				}catch(Exception ex){
					message.append("签到异常："+ex.getMessage());
					logger.error(String.format("签到[CourseOrder:%s]异常：", courseOrder.getId()), ex);
				}
			}
		}
		
		model.addAttribute("message", message.toString());
		
		siginin.setId("");
		return form(request,siginin, model);
	}
	
	@RequiresPermissions(value={"qd:siginin:delete","qd:sigin:delete"}, logical=Logical.OR)
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Siginin siginin, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				sigininService.delete(new Siginin(id));
			}
		}else{
			sigininService.delete(siginin);
		}
		
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/qd/siginin/?repage";
	}

}